package com.woniu.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * 取消订单的队列配置
 * 采用 死信交换机 + TTL 配置
 *
 * */

@Configuration
@Slf4j
public class RabbitDeadLatterOrderConfig {
    // 创建普通交换机
    @Bean
    public DirectExchange normalExchange() {
        return new DirectExchange("order.normal.exchange");
    }

    // 创建死信交换机
    @Bean
    public DirectExchange deadLatterExchange() {
        return new DirectExchange("order.dead.exchange");
    }

    /**
     *  普通订单队列
     *     队列名称
     *     指定私信交换机、
     *     死信路由键、
     *     队列过期时间
     *
     */
    @Bean
    public Queue orderNormalQueue() {
        return QueueBuilder
                .durable("order.normal.queue")
                .deadLetterExchange("order.dead.exchange")
                .deadLetterRoutingKey("order.dead.routingKey")
                .ttl(1 * 60 * 1000)     // 开发环境 1min
                .maxLength(3000)
                .build();
    }

    // 死信队列
    @Bean
    public Queue orderDeadLatterQueue() {
        return QueueBuilder
                .durable("order.dead.queue")
                .build();
    }

    // 普通交换机绑定普通队列
    @Bean
    public Binding orderNormalBinding(DirectExchange normalExchange, Queue orderNormalQueue) {
        return BindingBuilder
                .bind(orderNormalQueue)
                .to(normalExchange)
                .with("order.normal.routingKey");
    }

    // 死信交换机绑定死信队列
    @Bean
    public Binding orderDeadLatterBinding(DirectExchange deadLatterExchange, Queue orderDeadLatterQueue) {
        return BindingBuilder
                .bind(orderDeadLatterQueue)
                .to(deadLatterExchange)
                .with("order.dead.routingKey");
    }


}
